import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';
import 'package:like_button/like_button.dart';
import 'package:meco/views/index.dart';

import 'index.dart';

class DetailPage extends GetView<DetailController> {
  const DetailPage({super.key});

  // 主视图
  Widget _buildView() {
    return Stack(
      children: [
        // 背景图
        Positioned.fill(child: Image.asset(Images.startBg, fit: BoxFit.fill)),

        // 主要内容区域
        Column(
          children: [
            // 陶瓷图片区域 - 固定高度
            Container(
              width: double.infinity,
              height: 482.h,
              decoration: ShapeDecoration(
                gradient: LinearGradient(
                  begin: Alignment(0.50, -0.00),
                  end: Alignment(0.50, 1.00),
                  colors: [
                    Colors.black.withValues(alpha: 51),
                    Colors.black.withValues(alpha: 0),
                  ],
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12.r),
                ),
              ),
              child: Obx(() {
                final ceramic = controller.ceramicData.value;
                return ceramic?.imageUrl != null &&
                        ceramic!.imageUrl!.isNotEmpty
                    ? Image.asset(ceramic.imageUrl!, fit: BoxFit.cover)
                    : Image.asset(Images.ceramic1, fit: BoxFit.cover);
              }),
            ),

            // 可滚动内容区域
            Expanded(
              child: SingleChildScrollView(
                physics: BouncingScrollPhysics(),
                child: Padding(
                  padding: EdgeInsets.only(top: 57.h), // 为按钮留出空间
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 详情文字
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 26.w),
                        child: Obx(() {
                          final ceramic = controller.ceramicData.value;
                          return Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // 标题
                              if (ceramic?.title != null &&
                                  ceramic!.title!.isNotEmpty)
                                Text(
                                  ceramic.title!,
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 18.sp,
                                    fontFamily: 'Inter',
                                    fontWeight: FontWeight.w500,
                                    height: 1.3,
                                  ),
                                ),
                              if (ceramic?.title != null &&
                                  ceramic!.title!.isNotEmpty)
                                SizedBox(height: 12.h),
                              // 描述
                              Text(
                                ceramic?.description ??
                                    'Looking at these ceramics that contain tenderness and stories every day, it seems that time passes a little slower.',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 16.sp,
                                  fontFamily: 'Inter',
                                  fontWeight: FontWeight.w400,
                                  height: 1.44,
                                ),
                              ),
                            ],
                          );
                        }),
                      ),

                      SizedBox(height: 24.h),
                      Padding(
                        padding: EdgeInsets.only(left: 20.w),
                        child: Container(
                          width: 374.w,
                          height: 1.h,
                          color: Colors.white.withValues(alpha: 0.2),
                        ),
                      ),
                      SizedBox(height: 24.h),

                      // 评论区域
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 26.w),
                        child: _buildCommentList(),
                      ),

                      // 底部留些空间
                      SizedBox(height: 30.h),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),

        // 交互按钮 - 覆盖在内容上方
        Positioned(
          top: 450.h,
          left: 0,
          right: 0,
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 24.w),
            child: Row(
              children: [
                Container(
                  width: 178.w,
                  height: 66.h,
                  decoration: ShapeDecoration(
                    gradient: LinearGradient(
                      begin: Alignment(0.50, -0.00),
                      end: Alignment(0.50, 1.00),
                      colors: [
                        const Color(0xFF4580DD),
                        const Color(0xFF5592F1),
                      ],
                    ),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(33.50),
                    ),
                  ),
                  // 用户信息
                  child: Row(
                    children: [
                      SizedBox(width: 11.w),
                      // 用户头像
                      Obx(() {
                        final user = controller.creatorUser.value;
                        return GestureDetector(
                          onTap: () {
                            // 先尝试删除已存在的MeController实例，再跳转
                            try {
                              if (Get.isRegistered<MeController>()) {
                                Get.delete<MeController>(force: true);
                              }
                            } catch (e) {
                              print('删除MeController失败: $e');
                            }
                            Get.toNamed(
                              Routes.me,
                              arguments: {
                                'userId': user?.id,
                                'fromNavBar': false,
                                'forceRefresh': true,
                              },
                            );
                          },
                          child: CircleAvatar(
                            backgroundImage:
                                user?.avatar != null && user!.avatar!.isNotEmpty
                                    ? AssetImage(user.avatar!)
                                    : AssetImage(Images.avatar1),
                            radius: 22.r,
                          ),
                        );
                      }),
                      SizedBox(width: 6.w),

                      // 用户名
                      Obx(() {
                        final user = controller.creatorUser.value;
                        return Text(
                          user?.nickname ?? user?.username ?? 'Unknown',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w400,
                            height: 1,
                          ),
                        );
                      }),
                      Spacer(),
                      // 关注按钮
                      Obx(
                        () => LikeButton(
                          size: 25.sp,
                          isLiked: controller.isFollowed.value,
                          animationDuration: Duration(milliseconds: 800),
                          circleColor: CircleColor(
                            start: Color(0xFF3B5998),
                            end: Color(0xFF8B9DC3),
                          ),
                          bubblesColor: BubblesColor(
                            dotPrimaryColor: Color(0xFF3B5998),
                            dotSecondaryColor: Color(0xFF8B9DC3),
                            dotThirdColor: Color(0xFF4267B2),
                            dotLastColor: Color(0xFF5B7BD5),
                          ),
                          likeBuilder: (bool isLiked) {
                            return Icon(
                              isLiked
                                  ? IconFontIcons.iconFollowed
                                  : IconFontIcons.iconFollow,
                              size: 25.sp,
                              color: Colors.white,
                            );
                          },
                          onTap: (isLiked) async {
                            _handleFollowAction();
                            return controller.isFollowed.value;
                          },
                        ),
                      ),
                      SizedBox(width: 20.w),
                    ],
                  ),
                ),
                SizedBox(width: 52.w),

                // 收藏按钮
                Container(
                  width: 66.w,
                  height: 66.h,
                  decoration: ShapeDecoration(
                    gradient: LinearGradient(
                      begin: Alignment(0.50, -0.00),
                      end: Alignment(0.50, 1.00),
                      colors: [
                        const Color(0xFF4580DD),
                        const Color(0xFF5592F1),
                      ],
                    ),
                    shape: CircleBorder(),
                  ),
                  child: Center(
                    child: Obx(
                      () => LikeButton(
                        size: 24.sp,
                        isLiked: controller.isFavorited.value,
                        animationDuration: Duration(milliseconds: 800),
                        circleColor: CircleColor(
                          start: Color(0xFFFF5722),
                          end: Color(0xFFFFC107),
                        ),
                        bubblesColor: BubblesColor(
                          dotPrimaryColor: Color(0xFFFF5722),
                          dotSecondaryColor: Color(0xFFFFC107),
                          dotThirdColor: Color(0xFFFF9800),
                          dotLastColor: Color(0xFFF44336),
                        ),
                        likeBuilder: (bool isLiked) {
                          return Icon(
                            isLiked
                                ? IconFontIcons.iconLikeFill
                                : IconFontIcons.iconLike,
                            color: isLiked ? Colors.red : Colors.white,
                            size: 24.sp,
                          );
                        },
                        onTap: (isLiked) async {
                          _handleInteraction(InteractionType.favorite);
                          return controller.isFavorited.value;
                        },
                      ),
                    ),
                  ),
                ),

                SizedBox(width: 4.w),

                // 点赞按钮
                Container(
                  width: 66.w,
                  height: 66.h,
                  decoration: ShapeDecoration(
                    gradient: LinearGradient(
                      begin: Alignment(0.50, -0.00),
                      end: Alignment(0.50, 1.00),
                      colors: [
                        const Color(0xFF4580DD),
                        const Color(0xFF5592F1),
                      ],
                    ),
                    shape: CircleBorder(),
                  ),
                  child: Center(
                    child: Obx(
                      () => LikeButton(
                        size: 24.sp,
                        isLiked: controller.isLiked.value,
                        animationDuration: Duration(milliseconds: 800),
                        circleColor: CircleColor(
                          start: Color(0xFF00DDFF),
                          end: Color(0xFF0099CC),
                        ),
                        bubblesColor: BubblesColor(
                          dotPrimaryColor: Color(0xFF33B5E5),
                          dotSecondaryColor: Color(0xFF0099CC),
                          dotThirdColor: Color(0xFF00DDFF),
                          dotLastColor: Color(0xFF00AACC),
                        ),
                        likeBuilder: (bool isLiked) {
                          return Icon(
                            isLiked
                                ? IconFontIcons.iconGoodFill
                                : IconFontIcons.iconGood,
                            color: isLiked ? Colors.red : Colors.white,
                            size: 24.sp,
                          );
                        },
                        onTap: (isLiked) async {
                          _handleInteraction(InteractionType.like);
                          return controller.isLiked.value;
                        },
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  // 处理交互操作（点赞/收藏）
  void _handleInteraction(InteractionType type) {
    // 获取用户服务
    final userService = Get.find<UserService>();

    // 检查登录状态并执行操作
    userService.checkLoginThenExecute(
      loginRequiredMessage:
          type == InteractionType.like
              ? 'You need to login to like'
              : 'You need to login to collect',
      onLoggedIn: () {
        // 已登录，执行相应操作
        final userId = userService.currentUser.value!.id!;

        // 执行相应操作
        if (type == InteractionType.like) {
          controller.toggleLike(userId);
        } else {
          controller.toggleFavorite(userId);
        }
      },
    );
  }

  // 处理关注操作
  void _handleFollowAction() {
    // 获取用户服务
    final userService = Get.find<UserService>();

    // 检查登录状态并执行操作
    userService.checkLoginThenExecute(
      loginRequiredMessage: 'You need to login to follow',
      onLoggedIn: () {
        // 已登录，执行关注操作
        final currentUserId = userService.currentUser.value!.id!;

        // 不能关注自己
        if (currentUserId == controller.creatorUserId) {
          EasyLoading.showError('You cannot follow yourself');
          return;
        }

        // 执行关注/取消关注操作
        controller.toggleFollow(currentUserId);
      },
    );
  }

  // 构建评论列表
  Widget _buildCommentList() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 添加评论用户头像组件
        _buildCommentUsers(),

        SizedBox(height: 16.h),

        // 评论列表
        Obx(() {
          if (controller.isLoadingComments.value) {
            return SizedBox(
              height: 100.h,
              child: Center(
                child: CircularProgressIndicator(
                  color: Colors.white,
                  strokeWidth: 2,
                ),
              ),
            );
          }

          if (controller.comments.isEmpty) {
            return SizedBox(
              height: 100.h,
              child: Center(
                child: Text(
                  'Be the first to comment',
                  style: TextStyle(color: Colors.white70, fontSize: 16.sp),
                ),
              ),
            );
          }

          return ListView.separated(
            physics: NeverScrollableScrollPhysics(),
            padding: EdgeInsets.zero,
            shrinkWrap: true,
            itemCount: controller.comments.length,
            separatorBuilder: (context, index) => SizedBox(height: 16.h),
            itemBuilder: (context, index) {
              final comment = controller.comments[index];
              return _buildCommentItem(comment);
            },
          );
        }),

        SizedBox(height: 100.h),
      ],
    );
  }

  // 构建单个评论项
  Widget _buildCommentItem(CommentModel comment) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 用户头像和名称
            Row(
              children: [
                // 用户头像
                GestureDetector(
                  onTap: () {
                    // 先尝试删除已存在的MeController实例，再跳转
                    try {
                      if (Get.isRegistered<MeController>()) {
                        Get.delete<MeController>(force: true);
                      }
                    } catch (e) {
                      print('删除MeController失败: $e');
                    }
                    Get.toNamed(
                      Routes.me,
                      arguments: {
                        'userId': int.tryParse(comment.userId),
                        'fromNavBar': false,
                        'forceRefresh': true,
                      },
                    );
                  },
                  child: Container(
                    height: 42.h,
                    width: 42.w,
                    decoration: BoxDecoration(shape: BoxShape.circle),
                    child: ClipOval(
                      child:
                          comment.userAvatar.isNotEmpty
                              ? Image.asset(
                                comment.userAvatar,
                                fit: BoxFit.cover,
                              )
                              : Container(
                                color: Colors.grey[300],
                                child: Icon(
                                  Icons.person,
                                  size: 20.sp,
                                  color: Colors.grey[600],
                                ),
                              ),
                    ),
                  ),
                ),
                SizedBox(width: 10.w),
                // 用户名
                Text(
                  comment.userName,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),

            // 举报按钮
            GestureDetector(
              onTap: () {
                // 处理举报逻辑
                controller.reportComment(comment);
              },
              child: Icon(
                IconFontIcons.iconFrame,
                color: Colors.white70,
                size: 18.sp,
              ),
            ),
          ],
        ),

        SizedBox(height: 8.h),

        // 评论内容
        Text(
          comment.content,
          style: TextStyle(
            color: const Color(0xFFD1D1D1),
            fontSize: 14.sp,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w400,
            height: 1.5,
          ),
        ),

        SizedBox(height: 8.h),

        // 评论时间
        Text(
          _formatDateTime(comment.createdAt),
          style: TextStyle(
            color: Colors.white54,
            fontSize: 12.sp,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w400,
          ),
        ),
      ],
    );
  }

  // 格式化日期时间
  String _formatDateTime(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 365) {
      return '${difference.inDays ~/ 365} year ago';
    } else if (difference.inDays > 30) {
      return '${difference.inDays ~/ 30} months ago';
    } else if (difference.inDays > 0) {
      return '${difference.inDays} days ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours} hours ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes} minutes ago';
    } else {
      return 'just now';
    }
  }

  // 评论输入区域
  Widget _buildCommentInput(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(top: 2.h),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(30.r),
          topRight: Radius.circular(30.r),
        ),
      ),
      child: SafeArea(
        child: Container(
          padding: EdgeInsets.only(
            left: 20.w,
            right: 20.w,
            top: 24.h,
            bottom: 36.h,
          ),
          decoration: BoxDecoration(
            color: const Color(0xFF08306F),
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(28.r),
              topRight: Radius.circular(28.r),
            ),
          ),
          child: Row(
            children: [
              // 评论输入框
              Expanded(
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.51),
                    borderRadius: BorderRadius.circular(26.r),
                  ),
                  child: TextField(
                    controller: controller.commentController,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14.sp,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w400,
                    ),
                    decoration: InputDecoration(
                      hintText: 'Say something...',
                      hintStyle: TextStyle(
                        color: Colors.white,
                        fontSize: 14.sp,
                        fontFamily: 'Inter',
                        fontWeight: FontWeight.w400,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(vertical: 10.h),
                    ),
                  ),
                ),
              ),

              // 发送按钮
              SizedBox(width: 8.w),
              InkWell(
                onTap: () {
                  controller.addComment();
                  // 隐藏键盘
                  FocusScope.of(context).unfocus();
                },
                child: Container(
                  width: 96.w,
                  height: 52.h,
                  decoration: ShapeDecoration(
                    color: Colors.white.withValues(alpha: 0.51),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(26.r),
                    ),
                  ),
                  child: Center(
                    child: Text(
                      'Send',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 17.sp,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 构建评论用户头像组件
  Widget _buildCommentUsers() {
    return Obx(() {
      final isLoading = controller.isLoadingUsers.value;
      final commentUsers = controller.commentUsers;

      if (isLoading) {
        return SizedBox(
          height: 50.h,
          child: Center(
            child: SizedBox(
              width: 20.w,
              height: 20.h,
              child: CircularProgressIndicator(
                strokeWidth: 2.0,
                color: Colors.white,
              ),
            ),
          ),
        );
      }

      return Row(
        children: [
          // 评论用户头像
          if (commentUsers.isNotEmpty) ...[
            SizedBox(
              height: 44.h,
              width:
                  commentUsers.length > 1 ? 30.w * commentUsers.length : 44.w,
              child: Stack(
                children: List.generate(
                  commentUsers.length > 5 ? 5 : commentUsers.length,
                  (index) => Positioned(
                    left: index * 20.w,
                    child: Container(
                      height: 44.h,
                      width: 44.w,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        border: Border.all(color: Colors.white, width: 2),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1),
                            blurRadius: 4,
                            spreadRadius: 1,
                          ),
                        ],
                      ),
                      child: ClipOval(
                        child:
                            commentUsers[index].avatar != null &&
                                    commentUsers[index].avatar!.isNotEmpty
                                ? Image.asset(
                                  commentUsers[index].avatar!,
                                  fit: BoxFit.cover,
                                )
                                : Container(
                                  color: Colors.grey[300],
                                  child: Icon(
                                    Icons.person,
                                    size: 25.sp,
                                    color: Colors.grey[600],
                                  ),
                                ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
            SizedBox(width: 10.w),
            Text(
              '${commentUsers.length} comments',
              style: TextStyle(
                color: Colors.white70,
                fontSize: 14.sp,
                fontWeight: FontWeight.w400,
              ),
            ),
          ] else ...[
            // 没有评论用户时显示
            Container(
              height: 40.h,
              width: 40.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: Colors.white, width: 2),
              ),
              child: Center(
                child: Icon(
                  Icons.chat_bubble_outline,
                  size: 20.sp,
                  color: Colors.white,
                ),
              ),
            ),
            SizedBox(width: 10.w),
            Text(
              'No comments yet',
              style: TextStyle(
                color: Colors.white70,
                fontSize: 14.sp,
                fontWeight: FontWeight.w400,
              ),
            ),
          ],
        ],
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<DetailController>(
      init: DetailController(),
      id: "detail",
      builder: (_) {
        return Scaffold(
          extendBodyBehindAppBar: true,
          extendBody: true,
          appBar: AppBar(
            title: const Text("Share Details"),
            backgroundColor: Colors.transparent,
            elevation: 0,
            systemOverlayStyle: SystemUiOverlayStyle.light, // 状态栏文字为白色
            actions: [
              // 举报按钮
              IconButton(
                icon: Icon(IconFontIcons.iconReport, color: Colors.white),
                onPressed: () => controller.reportCeramic(),
              ),
            ],
          ),
          body: _buildView(),
          bottomSheet: _buildCommentInput(context),
        );
      },
    );
  }
}
